<?php

include "db.php";

class User{
    private $session_id;
    private $ip;
    private $status;
    private $db;
    private $table_name;
    private $lastactivity;

    function __construct()
    {
	$this->db = new Db;
	$this->db->db_connect();
	$this->table_name = 'user_table';
    }
    public function init($session_id,$ip,$lastactivity)
    {
	$this->session_id = $session_id;
	$this->ip = $ip;
	$this->status = 0;
	$this->lastactivity = $lastactivity;
    }
    public function init_for_db($session_id)
    {
	$result = $this->db->db_select($this->table_name,array('*'),'session_id = \''.$session_id.'\'');
	$row = mysql_fetch_array($result);
	$this->session_id = $row['session_id'];
	$this->ip = $row['ip'];
	$this->status = $row['status'];
	$this->lastactivity = $row['lastactivity'];
    }
    public function insert()
    {
	$this->db->db_insert($this->table_name,array(
	    'session_id'=>$this->session_id,
	    'ip'=>$this->ip,
	    'status'=>$this->status,
	    'lastactivity'=>$this->lastactivity
	)) or die("添加用户失败");
    }
    public function update_activity()
    {
	$this->db->db_update($this->table_name,'lastactivity',time()+180,'session_id=\''.$this->session_id.'\'');
    }
    public function set_status($status)
    {
	$this->status = $status;
	$this->db->db_update($this->table_name,'status',$this->status,'session_id=\''.$this->session_id.'\'');
    }
    public function is_exist()
    {
	$result = $this->db->db_select($this->table_name,array('session_id'),'session_id=\''.$this->session_id.'\'');
	if(!mysql_num_rows($result))
	    return FALSE;
	return TRUE;
    }
    // 寻找用户
    // 找到就随机返回一个用户的session_id
    // 找不到就返回FALSE
    public function find_user()
    {
	$result = $this->db->db_select($this->table_name,array('session_id'),'session_id != \''.$this->session_id.'\' && status = 1');
	$rows = mysql_num_rows($result);
	if($rows == 0)
	    return FALSE;
	while($row[] = mysql_fetch_array($result))
	    ;
	$index = rand(0,$rows-1);
	return $row[$index]['session_id'];
    }
    public function del()
    {
	$this->db->db_delete($this->table_name,'session_id=\''.$this->session_id.'\'');
    }
    public function del_unactivity()
    {
	$this->db->db_delete($this->table_name,'lastactivity<'.time());
    }
    public function get_status()
    {
	return $this->status;
    }
    public function get_session_id()
    {
	return $this->session_id;
    }
}

?>
